// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const setting = await db.collection('Setting').doc('5a93cec95edf0fc400679b4f23f37a84').get()
  let {
    op,
    type,
    src,
    price,
    selected_treasures,
    message
  } = event
  switch (op) {
    case 'buy':
      return buy()
      break;
    case 'sale':
      return sale()
      break;
    case 'getMyTreasure':
      return getMyTreasure();
      break;

  }

  async function buy() {
    let res = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).field({
      gold: true
    }).get()
    if (res.data[0].gold < price) {
      return "goldNotEnough"
    }

    //
    let treasure = await db.collection('Treasure').where({
      type: type,
      _openid: wxContext.OPENID
    }).get()

    if (treasure.data.length == 0) {
      await db.collection('Treasure').add({
        data: {
          type: type,
          src: src,
          _openid: wxContext.OPENID,
          amount: 1
        }
      })
    } else {
      await db.collection('Treasure').where({
        type: type,
        _openid: wxContext.OPENID,

      }).update({
        data: {
          amount: _.inc(1),
        }
      })
    }
        //
        await db.collection('User').where({
          _openid: wxContext.OPENID
        }).update({
          data: {
          
            gold: _.inc(parseInt(-price)),
          }
        })
    return "buy ok"
  }

  async function sale() {
    let res = await db.collection('Treasure').where({
      _openid: wxContext.OPENID,
      type: type
    }).field({
      amount: true
    }).get()
    if (res.data[0].amount <= 0) {
      return "TreasureNotEnough"
    }


    //
    await db.collection('Treasure').where({
      type: type,
      _openid: wxContext.OPENID,
    }).update({
      data: {
        amount: _.inc(-1),
      }
    })
    await db.collection('User').where({
      _openid: wxContext.OPENID
    }).update({
      data: {
      
        gold: _.inc(parseInt(price)),
      }
    })
    return "sale ok"
  }

  async function getMyTreasure() {
    let res = await db.collection('Treasure').where({
      _openid: wxContext.OPENID,
      amount: _.gt(0)
    }).orderBy('type', 'asc').get()
    let treasures = setting.data.treasures
    let myTreasures = res.data

    for (let i = 0; i < myTreasures.length; i++) {
      for (let j = 0; j < treasures.length; j++) {
        if (myTreasures[i].type == treasures[j].type) {
          myTreasures[i].price = treasures[j].price
          myTreasures[i].title = treasures[j].title
          myTreasures[i].src = treasures[j].src
        }
      }
    }

    return myTreasures
  }


}